package net.adriana.esaytool.util;

import java.sql.*;

import net.adriana.esaytool.Logger;
import net.adriana.esaytool.PropertyReader;

/**
 * 
 * 
 * @author Administrator
 *
 */
public class MetaDataUtil {
	private static String DRIVER;
	private static String URL;
	public static String DATABASE;
	public static String USER;
	public static String PASSWORD;
	private static Connection con;
	private static DatabaseMetaData md;
	
	static{
		try {
			DRIVER = PropertyReader.get("driver");
			URL = PropertyReader.get("url");
			USER = PropertyReader.get("user");
			PASSWORD = PropertyReader.get("password");
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			Logger.log(Logger.ERROR, "数据库驱动加载失败" + e.getMessage());
		}
	}
	
	public static  Connection getConnection() throws SQLException{
		Connection conn = DriverManager.getConnection(URL + DATABASE,USER,PASSWORD);
		if(conn!=null)Logger.log(Logger.DEBUG, "数据库连接成功");
		else Logger.log(Logger.ERROR, "数据库连接失败："
				+ "[ 数据库名：" + DATABASE + " 用户名："+USER+" 密码："+PASSWORD+" ]");
		return conn;
	}
	
	public static void closeConnection() throws SQLException{
		if(con!=null) con.close();
	}
	
	public static DatabaseMetaData getMetaData() throws SQLException{
		con = getConnection();
		DatabaseMetaData dbmd = con.getMetaData();
		if(dbmd!=null)Logger.log(Logger.DEBUG, "数据库元数据获取成功");
		else Logger.log(Logger.ERROR, "数据库元数据获取失败");
		return dbmd;
	}
	
	public static ResultSet getTables(String tableName,String[] tableTypes) throws SQLException{
		md = getMetaData();
		ResultSet rs = md.getTables(con.getCatalog(), DATABASE, null, tableTypes);
		if(rs!=null)Logger.log(Logger.DEBUG,"表内容获取成功" + getMessage(tableName,null));
		else Logger.log(Logger.ERROR, "表内容获取失败：" + getMessage(tableName,null));
		return rs;
	}
	
	public static ResultSet getColumns(String tableName,String columnName) throws SQLException{
		md = getMetaData();
		ResultSet rs = md.getColumns(con.getCatalog(), DATABASE, tableName, columnName);
		if(rs!=null)Logger.log(Logger.DEBUG,"列信息获取成功" + getMessage(tableName,columnName));
		else Logger.log(Logger.ERROR, "列信息获取失败：" + getMessage(tableName,columnName));
		return rs;
	}
	
	public static ResultSet getPrimaryKey(String tableName)throws SQLException{
		md = getMetaData();
		ResultSet rs = md.getPrimaryKeys(null, DATABASE, tableName);
		if(rs!=null)Logger.log(Logger.DEBUG,"主键信息获取成功" + getMessage(tableName,null));
		else Logger.log(Logger.ERROR, "主键信息获取失败：" + getMessage(tableName,null));
		return rs;
	}
	
	public static String getMessage(String tableName,String columnName){
		if(tableName == null) return "[ 数据库：" + DATABASE + " ]";
		else if(columnName == null) return "[ 数据库：" + DATABASE + " 表：" + tableName + " ]";
		return  "[ 数据库：" + DATABASE + " 表：" + tableName + " 列：" + columnName + " ]";
	}

}
